package com.nightsoul.shiro.test.permission;

import org.apache.shiro.authz.Permission;
import org.apache.shiro.util.StringUtils;

public class BitPermission implements Permission {
	private String resourceIdentity;
	private int permissionBit;
	private String instanceId;
	
	public BitPermission(String permissionString) {
		String[] splits = permissionString.split("\\+");
		if(splits.length > 1) {
			resourceIdentity = splits[1];
		}
		if(!StringUtils.hasLength(resourceIdentity)) {
			this.resourceIdentity = "*";
		}
		if(splits.length > 2) {
			permissionBit = Integer.parseInt(splits[2]);
		}
		if(splits.length > 3) {
			this.instanceId = splits[3];
		}
		
		if(!StringUtils.hasLength(instanceId)) {
			instanceId = "*";
		}
	}

	@Override
	public boolean implies(Permission p) {
		if(!(p instanceof BitPermission)) {
			return false;
		}
		
		BitPermission other = (BitPermission) p;
		if(!("*".equals(this.resourceIdentity) || this.resourceIdentity.equals(other.resourceIdentity))) {  
            return false;  
        }  
        if(!(this.permissionBit ==0 || (this.permissionBit & other.permissionBit) != 0)) {  
            return false;  
        }  
        if(!("*".equals(this.instanceId) || this.instanceId.equals(other.instanceId))) {  
            return false;  
        }  
		
		return true;
	}

}
